#!/bin/bash

LOCK=/run/lock/gtk-bookmark-update-lock
BOOKMARKS=/root/.gtk-bookmarks

# make sure it exists
mkdir -p /run/lock

# make sure to avoid parallel execution by using mkdir as lock
while true; do
   mkdir $LOCK 2>/dev/null
   if [ $? = 0 ]; then
      break
   fi
done

cat $BOOKMARKS | fgrep -v ///media/ | fgrep -v "file:/// /" | egrep -v '^$' > $BOOKMARKS.tmp 2>/dev/null
ls -1 /media | sort | while read LINE; do
   echo "file:///media/$LINE $LINE" >> $BOOKMARKS.tmp
done

echo "file:/// /" >> $BOOKMARKS.tmp # add root at the beginning

mv -f $BOOKMARKS.tmp $BOOKMARKS

rmdir $LOCK
